<template>
  <div>
    <div class="exam-list">
      <el-table
        :data="examList"
        row-key="id"
        lazy
        :load="loadRollup"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        size="mini"
        header-row-class-name="table-header"
      >
        <el-table-column label="试卷名称" width="260">
          <template slot-scope="scope">
            <div class="exam-title">
              <div class="ellipsis">{{ scope.row.paper.title }}</div>
              <div v-if="$util.isDef(scope.row.product_type_id)" class="tag">
                {{ scope.row.product_type_id == 8 ? '公开考试' : '套卷' }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="考试时间" width="240">
          <template
            slot-scope="scope"
            v-if="$util.isUndef(scope.row.product_type_id) || scope.row.product_type_id == 8"
          >
            {{ getFormateDate(scope.row.config.exam_stime, scope.row.config.exam_etime) }}
          </template>
        </el-table-column>
        <el-table-column label="已作答次数">
          <template
            slot-scope="scope"
            v-if="$util.isUndef(scope.row.product_type_id) || scope.row.product_type_id == 8"
          >
            {{ scope.row.answer_count }}
          </template>
        </el-table-column>
        <el-table-column label="可作答次数">
          <template
            slot-scope="scope"
            v-if="$util.isUndef(scope.row.product_type_id) || scope.row.product_type_id == 8"
          >
            {{ scope.row.config.exam_number || '无限制' }}
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template
            slot-scope="scope"
            v-if="$util.isUndef(scope.row.product_type_id) || scope.row.product_type_id == 8"
          >
            <span v-if="scope.row.answer_count" class="correct">已作答</span>
            <span v-else>未作答</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template
            slot-scope="scope"
            v-if="$util.isUndef(scope.row.product_type_id) || scope.row.product_type_id == 8"
          >
            <el-button
              @click="onExam(scope.row)"
              type="text"
              size="small"
              :disabled="scope.row.paper_exist == 0"
              >去考试</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <EduPagination @handleCurrentChange="handleCurrentChange" align="right"></EduPagination>

    <!-- 人脸验证 -->
    <EduFaceVerify
      v-if="faceVisible"
      :visible.sync="faceVisible"
      scene_key="exam"
      :scene_id="paperId"
      scene_type="1"
      @cancel="handleFaceSuccess"
    ></EduFaceVerify>
  </div>
</template>

<script>
import { parseTime } from '@/utils/filters.js'
import EduPagination from '@/components/EduPagination'
import EduFaceVerify from '@/components/EduFaceVerify'
import { mapGetters } from 'vuex'
export default {
  components: {
    EduPagination,
    EduFaceVerify
  },
  data() {
    return {
      examList: [],
      paperId: 0, // 考试id
      faceVisible: false
    }
  },
  computed: {
    ...mapGetters({
      faceStatus: 'projectSetting/getGlobFaceStatus'
    })
  },
  methods: {
    getUserExamOrderList() {
      this.$api.getUserExamRecordOrder(
        {
          page: this.$store.getters['paginate/page'],
          count: 12
        },
        res => {
          const { data } = res
          this.examList = data.data.map((item, index) => {
            item.id = index
            if (item.product_type_id == 10) {
              item.hasChildren = true
              item.children = []
            }
            return item
          })
          this.$store.dispatch('paginate/setPaginate', {
            listRows: 12,
            total: data.total
          })
        }
      )
    },
    loadRollup(tree, treeNode, resolve) {
      this.$api.getUserExamRecordRollup(tree.paper.id, res => {
        const { data } = res
        resolve(data)
      })
    },
    // 分页
    handleCurrentChange() {
      this.getUserExamOrderList()
    },
    // 去考试
    onExam(item) {
      if (item.exam_open == 1) {
        if (this.$util.isDef(item.product_type_id) && item.product_type_id == 8) {
          if (item.config.face_verification == 1) {
            this.paperId = item.paper.id
            this.faceEntrance()
          } else {
            this.$router.push({
              path: '/exam/paper/topic',
              query: {
                id: item.paper.id
              }
            })
          }
        } else {
          if (item.exam_rest_num == 1) {
            this.$message.info('考试次数已用完')
          } else {
            this.$router.push({
              path: '/exam/rollup/topic',
              query: {
                rollup_id: item.rollup_id,
                paper_id: item.paper_id
              }
            })
          }
        }
      } else {
        this.$message.info('暂未开放')
      }
    },
    // 人脸验证成功
    handleFaceSuccess() {
      this.$router.push({
        path: '/exam/paper/topic',
        query: {
          id: this.paperId
        }
      })
    },
    // 窗口
    faceEntrance() {
      // 已认证
      if (this.faceStatus) {
        this.$messageBox
          .confirm('请进行人脸验证', {
            type: 'none',
            center: true,
            confirmButtonText: '去验证'
          })
          .then(() => {
            this.faceVisible = true
          })
          .catch(() => {})
      } else {
        this.$messageBox
          .confirm('未完成人脸认证，请先去认证', {
            type: 'none',
            center: true,
            confirmButtonText: '去认证'
          })
          .then(() => {
            this.$router.push({
              path: '/my/profile/face_verify',
              query: {
                back: 1
              }
            })
          })
          .catch(() => {})
      }
    },
    getFormateDate(stime, etime) {
      if (this.$util.isEmpty(stime) || this.$util.isEmpty(etime)) return '永久有效'
      if (stime.toString().length === 10) stime *= 1000
      if (etime.toString().length === 10) etime *= 1000
      const now = new Date()

      const sdate = new Date(stime)
      const edate = new Date(etime)

      // 同一年
      const isSameYear = (timestamp1, timestamp2) => {
        return timestamp1.getFullYear() === timestamp2.getFullYear()
      }

      // 同一天
      const isSameDay = (timestamp1, timestamp2) => {
        return (
          timestamp1.getFullYear() === timestamp2.getFullYear() &&
          timestamp1.getMonth() === timestamp2.getMonth() &&
          timestamp1.getDate() === timestamp2.getDate()
        )
      }

      const cFormat = '{y}-{m}-{d} {h}:{i}'
      const mFormat = '{m}-{d} {h}:{i}'
      const hFormat = '{h}:{i}'

      // 今年
      if (isSameYear(now, sdate)) {
        if (isSameDay(sdate, edate)) {
          return parseTime(stime, mFormat) + '-' + parseTime(edate, hFormat)
        } else {
          return parseTime(stime, mFormat) + ' 至 ' + parseTime(edate, mFormat)
        }
      } else {
        if (isSameDay(sdate, edate)) {
          return parseTime(stime, cFormat) + '-' + parseTime(edate, hFormat)
        } else {
          return parseTime(stime, cFormat) + ' 至 ' + parseTime(edate, mFormat)
        }
      }
    }
  },
  mounted() {
    this.getUserExamOrderList()
  },
  destroyed() {
    this.$store.commit('paginate/SET_PAGINATE_DEFAULT')
  }
}
</script>

<style lang="scss" scoped>
.exam-list {
  margin-top: 16px;
  .el-table {
    ::v-deep .table-header th {
      background-color: #f6f9ff;
    }
  }
  .exam-title {
    display: inline-flex;
    align-items: center;
  }
  .ellipsis {
    max-width: 170px;
    @include ellipsis();
  }
  .tag {
    padding: 4px 5px;
    font-size: 12px;
    font-weight: 400;
    color: #606266;
    line-height: 17px;
    background: #efefef;
    border-radius: 2px;
    margin-left: 5px;
    white-space: nowrap;
  }
  .correct {
    color: $text-color-free;
  }
  .error {
    color: $text-color-error;
  }
}
</style>
